<template>
    <div class="order-page">
        <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
            <el-tab-pane label="未支付" name="未支付">
                <el-table :data="notPay" style="width: 100%" :row-style="getRowStyle" v-if="notPay"
                    :header-cell-style="getHeaderStyle">
                    <el-table-column type="expand">
                        <template #default="props">
                            <div class="table-expend-style">
                                <el-table :data="props.row.ticketVOList" style="width: 100%" :row-style="getRowStyle"
                                    :header-cell-style="getHeaderStyle">
                                    <el-table-column type="index" label="ID" />
                                    <el-table-column prop="cinemaName" label="影院名字" />
                                    <el-table-column prop="roomName" label="影厅名字" />
                                    <el-table-column prop="movieName" label="电影名字" />
                                    <el-table-column prop="moviePrice" label="电影票价" />
                                    <el-table-column prop="date" label="播放日期" />
                                    <el-table-column prop="during" label="时间区间" />
                                    <el-table-column prop="cinemaAddress" label="影院地址" />
                                </el-table>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column type="index" label="ID" />
                    <el-table-column prop="orderId" label="订单编号" />
                    <el-table-column prop="total" label="总计" />
                    <el-table-column prop="createTime" label="创建时间" />
                    <el-table-column align="center">
                        <template #header>
                            <span>操作</span>
                        </template>
                        <template #default="scope">
                            <el-button size="small" type="primary" @click="handlePay(scope.$index, scope.row)">支付
                            </el-button>
                            <el-button size="small" type="danger" @click="handleCancel(scope.$index, scope.row)">取消
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </el-tab-pane>
            <el-tab-pane label="已支付" name="已支付">
                <el-table :data="paied" style="width: 100%" :row-style="getRowStyle" v-if="paied"
                    :header-cell-style="getHeaderStyle">
                    <el-table-column type="expand">
                        <template #default="props">
                            <div class="table-expend-style">
                                <el-table :data="props.row.ticketVOList" style="width: 100%" :row-style="getRowStyle"
                                    :header-cell-style="getHeaderStyle">
                                    <el-table-column type="index" label="ID" />
                                    <el-table-column prop="cinemaName" label="影院名字" />
                                    <el-table-column prop="roomName" label="影厅名字" />
                                    <el-table-column prop="movieName" label="电影名字" />
                                    <el-table-column prop="moviePrice" label="电影票价" />
                                    <el-table-column prop="date" label="播放日期" />
                                    <el-table-column prop="during" label="时间区间" />
                                    <el-table-column prop="cinemaAddress" label="影院地址" />
                                    <el-table-column align="center">
                                        <template #header>
                                            <span>操作</span>
                                        </template>
                                        <template #default="scope">
                                            <el-button size="small" type="warning" @click="handleCheck(scope.row)" v-if="scope.row.checkStatus ==0 ">检票
                                            </el-button>
                                            <el-button size="small" type="danger" @click="handleRate(scope.row)" v-if="scope.row.checkStatus == 1">评价
                                            </el-button>
                                        </template>
                                    </el-table-column>
                                </el-table>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column type="index" label="ID" />
                    <el-table-column prop="orderId" label="订单编号" />
                    <el-table-column prop="total" label="总计" />
                    <el-table-column prop="createTime" label="创建时间" />
                    <el-table-column prop="payTime" label="支付时间" />
                    <el-table-column align="center">
                        <template #header>
                            <span>操作</span>
                        </template>
                        <template #default="scope">
                            <el-button size="small" type="primary" @click="handleReset(scope.row)">重选/退票
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </el-tab-pane>
        </el-tabs>
    </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { ElMessage, TabsPaneContext } from 'element-plus'
import { getOrderVO, payOrder, cancelOrder } from '../../../api/order'
import { useRouter } from 'vue-router'

interface IOrder {
    payTime?: Date
    orderId: number
    createTime: Date
    payStatus: number
    ticketVOList: ITicketVO[]
}

interface ITicketVO {
    movieName: string
    moviePrice: string
    cinemaName: string
    roomName: string
    cinemaAddress: string
    start: number
    date: string
    during: string
    end: number
    cinemaId: number
    orderId: number
    scheduleId: number
    movieId: number,
    ticketId: number,
    payStatus: number,
    checkStatus:number
}

let orderVO = ref<IOrder[]>([])
const router = useRouter()

const notPay = computed(() => {
    let arr: IOrder[] = []

    orderVO.value.forEach((item: IOrder) => {
        let filter = item.ticketVOList.filter((item2: ITicketVO) => {
            return item2.payStatus == 0
        })
        let len = filter.length
        if (len > 0) {
            arr.push({
                ...item,
                ticketVOList: filter
            })
        }
    })

    return arr
})

const paied = computed(() => {


    let arr: IOrder[] = []

    orderVO.value.forEach((item: IOrder) => {
        let filter = item.ticketVOList.filter((item2: ITicketVO) => {
            return item2.payStatus == 1
        })
        let len = filter.length
        if (len > 0) {
            arr.push({
                ...item,
                ticketVOList: filter
            })
        }
    })

    return arr



})

const userId = JSON.parse(window.sessionStorage.getItem("currentUser")!).userId

const activeName = ref('未支付')

getOrderVO({ userId: userId }).then((res: any) => {
    if (res.code == 200) {
        orderVO.value = res.data
        console.log(res.data)
    } else {
        ElMessage.error("获得订单失败")
    }
})


const handleClick = (tab: TabsPaneContext, event: Event) => {
    console.log(tab, event)
}

const handlePay = (index: number, row: IOrder) => {
    payOrder({ orderId: row.orderId }).then(function (res: any) {
        if (res.code == 200) {
            getOrderVO({ userId: userId }).then((res: any) => {
                if (res.code == 200) {
                    orderVO.value = res.data
                    console.log(res.data)
                    ElMessage.success("支付成功")
                } else {
                    ElMessage.error("支付订单失败")
                }
            })
            
        } else {
            ElMessage.error("支付订单失败")
        }
    })
}

const handleCancel = (index: number, row: IOrder) => {
    cancelOrder({ orderId: row.orderId }).then((res: any) => {
        if (res.code == 200) {
            getOrderVO({ userId: userId }).then((res: any) => {
                if (res.code == 200) {
                    orderVO.value = res.data
                    console.log(res.data)
                    ElMessage.success("订单取消成功")
                } else {
                    ElMessage.error("订单取消失败")
                }
            })
            
        } else {
            ElMessage.error("取消订单失败")
        }
    })
}

const handleReset = (row: IOrder) => {
    // 通过电影的播放时间与现在的时间的对比，判断是否进行这一次的跳转
    let now = new Date()
    let dateParam = row.ticketVOList[0].date.split("-")
    let hourParam = (row.ticketVOList[0].start - 30) / 60
    let minParam = (row.ticketVOList[0].start - 30) % 60
    let playTime = new Date(
        parseInt(dateParam[0]), parseInt(dateParam[1]) - 1, parseInt(dateParam[2]), hourParam, minParam
    )
    if(now > playTime) {
        console.log(now,playTime)
        ElMessage.error("电影播放前的30分钟不允许重选或退票")
        return
    }
    router.push({
        path: '/ticket/buy',
        query: {
            date: row.ticketVOList[0].date,
            cinemaId: row.ticketVOList[0].cinemaId,
            movieId: row.ticketVOList[0].movieId,
            scheduleId: row.ticketVOList[0].scheduleId,
            orderId: row.orderId
        }
    })
}

const handleRate = (row:ITicketVO) => {
    router.push({
        path: '/rate',
        query: {
            movieId: row.movieId,
        }
    })
}
const handleCheck = (row: ITicketVO) => {
    router.push({
        path: '/ticket/check',
        query: {
            ticketId: row.ticketId
        }
    })
}

const getRowStyle = (data: any): object => {
    return {
        'backgroundColor': '#efefef',
        'textAlign': 'center'
    }
}

const getHeaderStyle = (data: any): object => {
    return {
        'backgroundColor': '#efefef',
    }
}
</script>

<style>
.table-expend-style,
.order-page .el-table tr {
    background-color: rgb(239, 239, 239);
}

.order-page .el-table__expanded-cell {
    background-color: transparent;
}
</style>

<style lang='less' scoped>
.order-page {
    padding: 20px 0px;
}

.table-expend-style {
    padding: 0 59px;
}
</style>

